package com.mis.pos.common.config;

import com.mis.pos.entity.SysPermission;
import com.mis.pos.entity.SysRole;
import com.mis.pos.entity.UserEntity;
import com.mis.pos.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @description: 自定义验证
 * @author: yuxiang
 * @create: 2019-12-12 16:10
 **/
public class MyShiroRealm extends AuthorizingRealm {

    Logger logger = LoggerFactory.getLogger(AuthorizingRealm.class);

    @Resource
    private UserService userService;



    //返回认证信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        UserEntity userEntity = (UserEntity) principalCollection.getPrimaryPrincipal();
        //授权信息
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for (SysRole sysRole: userEntity.getRoles()){
            simpleAuthorizationInfo.addRole(sysRole.getName());
            for (SysPermission permission :
                    sysRole.getPermissions()) {
                simpleAuthorizationInfo.addStringPermission(permission.getName());
            }
        }
        return simpleAuthorizationInfo;
    }

    //身份验证，账号密码是否正确
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {


        //获取用户输入的账户
        String username = (String) authenticationToken.getPrincipal();
        logger.info("用户名"+username);
        //通过username从数据库中查找实体
        UserEntity userEntity = userService.findByUsername(username);
        if (userEntity == null){
            return null;
        }

        //返回的身份验证信息
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                userEntity,//用户名
                userEntity.getPassword(), //密码
                ByteSource.Util.bytes(userEntity.getSalt()),//salt = username + salt
                getName() //realm name

        );
        return simpleAuthenticationInfo;
    }
}
